package demo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;



public class HibernateDemo {
    public static void main(String[] args) {
        SessionFactory factory = new Configuration().configure("hibernate.cfg.xml")
                .addAnnotatedClass(CollaCat.class)
                .addAnnotatedClass(CollaCatIC.class)
                .buildSessionFactory();

        Session session = null;
        
        try {
            // Start transaction with openSession()
            session = factory.openSession();
            session.beginTransaction();

            // Create a new CollaCat and associated CollaCatIC
            CollaCat collaCat = new CollaCat();
            collaCat.setCategoryName("Finance");

            CollaCatIC criteria1 = new CollaCatIC();
            criteria1.setIssueCriteria("Loan Criteria");

            CollaCatIC criteria2 = new CollaCatIC();
            criteria2.setIssueCriteria("Credit Criteria");

            collaCat.addIssueCriteria(criteria1);
            collaCat.addIssueCriteria(criteria2);

            // Save CollaCat, cascading to CollaCatIC
            session.save(collaCat);

            session.getTransaction().commit();

            // Remove one issueCriteria to demonstrate orphan removal
            session = factory.openSession();  // Re-open session
            session.beginTransaction();

            CollaCat existingCat = session.get(CollaCat.class, collaCat.getId());
            existingCat.removeIssueCriteria(criteria1);
            session.save(existingCat);
            
            session.flush(); 
            session.getTransaction().commit();

        } catch (Exception e) {
            if (session != null) {
                session.getTransaction().rollback(); // Rollback in case of error
            }
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
            factory.close();
        }
    }
}


